﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Uco.Models;
using Uco.Infrastructure;
using System.Configuration;
using System.Web.Security;
using System.Web.Caching;

namespace Uco
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalAttribute()
        {
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PhoneAttribute), typeof(RegularExpressionAttributeAdapter));
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
            routes.IgnoreRoute("{*robotstxt}", new { robotstxt = @"(.*/)?robots.txt(/.*)?" });

            routes.MapRoute("ImagesThumbnail","Image",new { controller = "Images", action = "GetImage"});
            routes.MapRoute("Captcha","Image",new { controller = "Captcha", action = "Get" });
            routes.MapRoute("HomePage","", new { controller = "Page", action = "LanguagePage", name = "root" });

            foreach (Type item in SF.GetAbstractPageChildClasses())
            {
                routes.MapRoute(item.Name, SF.GetTypeRouteUrl(item) + "/{name}", new { controller = "Page", action = item.Name });
            }

            routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Page", action = "Home", id = UrlParameter.Optional } );
            routes.MapRoute("Default_Lang", "{lang}/{controller}/{action}/{id}", new { controller = "Page", action = "Home", id = UrlParameter.Optional });
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalAttribute();
            RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders.Add(typeof(AbstractPage), new AbstractPageBinder());
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            if (Request.UrlReferrer != null) SF.SetCookie("Referal", Request.UrlReferrer.ToString());
        }

        protected void Application_BeginRequest(Object source, EventArgs e)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext context = app.Context;
            FirstRequestInitialization.Initialize(context);
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception objErr = Server.GetLastError().GetBaseException();
            if (objErr is HttpException) SF.LogHttpError((HttpException)objErr);
            else SF.LogError(objErr);
        }

        public override string GetVaryByCustomString(HttpContext context, string arg)
        {
            if (arg == "LangCode")
            {
                return System.Threading.Thread.CurrentThread.CurrentCulture.Name;
            }
            else if (arg == "CleanCacheGuid")
            {
                object o = context.Application["CleanCacheGuid"];
                if (o == null)
                {
                    o = Guid.NewGuid();
                    context.Application["CleanCacheGuid"] = o;
                }
                return o.ToString();
            }
            else if (arg == "LangCodeAndCleanCacheGuid")
            {
                object o = context.Application["CleanCacheGuid"];
                if (o == null)
                {
                    o = Guid.NewGuid();
                    context.Application["CleanCacheGuid"] = o;
                }
                return System.Threading.Thread.CurrentThread.CurrentCulture.Name + o.ToString();
            }

            return base.GetVaryByCustomString(context, arg);
        }


    }
}